﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

using FinalProject.BL;

namespace FinalProject.Gui
{
    public partial class DocumentManagerForm : Form
    {
        private Guid _selectedID = Guid.Empty;

        private bool _editMode = false;

        public DocumentManagerForm()
        {
            InitializeComponent();
            this.InitialEvents();

            this.cbxKH.DropDownStyle = ComboBoxStyle.DropDownList;
            this.cbxSP.DropDownStyle = ComboBoxStyle.DropDownList;
            this.cbxNV.DropDownStyle = ComboBoxStyle.DropDownList;
            this.txtMaHD.ReadOnly = true;
            this.grvDocument.AutoGenerateColumns = false;
            this.grvDocument.SelectionMode = DataGridViewSelectionMode.FullRowSelect;

            this.grvDetail.ReadOnly = true;
            this.grvDetail.AutoGenerateColumns = false;
            this.grvDetail.AllowUserToAddRows = false;

            this.btnSave.Visible = false;
            this.btnCancel.Visible = false;
        }

        #region >>Events<<

        private void InitialEvents()
        {
            this.Load += new System.EventHandler(this.DocumentManagerForm_Load);
            this.grvDocument.SelectionChanged += new EventHandler(grvDocument_SelectionChanged);

            this.txtMaHD.Validated += new EventHandler(txtMaHD_Validated);
            this.cbxSP.SelectedIndexChanged += new EventHandler(cbxSP_SelectedIndexChanged);
        }

        private void cbxSP_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (this.cbxSP.SelectedValue == null || !(this.cbxSP.SelectedValue is Guid))
            {
                return;
            }
            Guid itemID = Guid.Parse(this.cbxSP.SelectedValue.ToString());
            this.txtDonGia.Text = ManagerDocumentBL.LoadItemAmount(itemID).ToString();
        }

        private void txtMaHD_Validated(object sender, EventArgs e)
        {
            if (!this._editMode) return;
            if (string.IsNullOrWhiteSpace(this.txtMaHD.Text))
            {
                Ultilities.GetErrorMessage("Vui lòng không để trống");
            }
            else if (ManagerDocumentBL.CheckExist(this.txtMaHD.Text))
            {
                Ultilities.GetErrorMessage("Trùng mã hoá đơn");
            }

        }

        private void grvDocument_SelectionChanged(object sender, EventArgs e)
        {
            if (this._editMode)
            {
                return;
            }
            if (this.grvDocument.SelectedRows.Count <= 0) return;
            DataGridViewRow selectedRow = this.grvDocument.SelectedRows[0];
            if (selectedRow == null || selectedRow.Cells == null || selectedRow.Cells.Count == 0) return;

            this.LoadData(selectedRow);
        }

        private void DocumentManagerForm_Load(object sender, EventArgs e)
        {
            this.grvDocument.DataSource = ManagerDocumentBL.GetALLDocumentItems();
            this.LoadDataToCombobox();
        }
        #endregion

        #region >>Methods<<

        private void LoadData(DataGridViewRow selectedRow)
        {
            if (selectedRow == null) return;

            this._selectedID = Guid.Parse(selectedRow.Cells[ID_HD].Value.ToString());

            this.txtMaHD.Text = selectedRow.Cells[MA_HD].Value.ToString();
            this.dpkHD.Value = Convert.ToDateTime(selectedRow.Cells[NGAY_HD].Value);
            this.cbxKH.SelectedValue = Guid.Parse(selectedRow.Cells[ID_NV].Value.ToString());
            this.cbxNV.SelectedValue = Guid.Parse(selectedRow.Cells[ID_KH].Value.ToString());

            this.BindDataToDetail(_selectedID);
        }

        private void BindDataToDetail(Guid invoiceID)
        {
            var dataSource = ManagerDocumentBL.GetAllDetail(invoiceID);
            if (dataSource != null)
                this.grvDetail.DataSource = dataSource;
        }

        private void LoadDataToCombobox()
        {
            this.cbxKH.DataSource = new BindingSource(ManagerDocumentBL.GetAllCustomerCode(), null);
            this.cbxKH.DisplayMember = "Value";
            this.cbxKH.ValueMember = "Key";

            this.cbxNV.DataSource = new BindingSource(ManagerDocumentBL.GetAllEmployeeCode(), null);
            this.cbxNV.DisplayMember = "Value";
            this.cbxNV.ValueMember = "Key";

            this.cbxSP.DataSource = new BindingSource(ManagerDocumentBL.GetAllItemCode(), null);
            this.cbxSP.DisplayMember = "Value";
            this.cbxSP.ValueMember = "Key";
        }

        private void SwitchToEditMode(bool isEdit)
        {
            this._editMode = isEdit;
            this.btnSave.Visible = isEdit;
            this.btnCancel.Visible = isEdit;

            this.btnAddInvoice.Visible = !isEdit;
            this.btnDeleteInvoice.Visible = !isEdit;
        }

        private void CancelModified()
        {
            this._editMode = false;
            this.txtMaHD.ReadOnly = true;

            if (this.grvDocument.SelectedRows.Count <= 0) return;
            DataGridViewRow selectedRow = this.grvDocument.SelectedRows[0];
            if (selectedRow == null || selectedRow.Cells == null || selectedRow.Cells.Count == 0) return;

            this.LoadData(selectedRow);
            this.SwitchToEditMode(this._editMode);
        }

        private DocumentItem CreateOrUpdateDocumentItem(DocumentItem item)
        {
            if (item == null)
            {
                item = new DocumentItem();
                item.InvoiceCode = this.txtMaHD.Text;
            }

            item.CustomerID = Guid.Parse(this.cbxKH.SelectedValue.ToString());
            item.CreateDate = this.dpkHD.Value;
            item.EmployeeID = Guid.Parse(this.cbxNV.SelectedValue.ToString());

            return item;
        }

        private IList<DocumentDetailItem> GetAlllDetail()
        {
            IList<DocumentDetailItem> result = new List<DocumentDetailItem>();
            foreach (DataGridViewRow row in this.grvDetail.Rows)
            {
                DocumentDetailItem item = new DocumentDetailItem();
                item.ItemID = Guid.Parse(row.Cells[DETAIL_SP_ID].Value.ToString());
                item.Quantity = Convert.ToInt32(row.Cells[DETAIL_QUANTITY].Value);

                result.Add(item);
            }
            return result;
        }

        private void RefreshGridView()
        {
            this.grvDocument.DataSource = ManagerDocumentBL.GetALLDocumentItems();
            
        }
        #endregion

        private void btnAddInvoice_Click(object sender, EventArgs e)
        {
            this.SwitchToEditMode(true);

            this.txtMaHD.Enabled = true;
            this.txtMaHD.ReadOnly = false;

            this._selectedID = Guid.Empty;
            this.txtMaHD.Text = string.Empty;
            this.cbxKH.SelectedIndex = 0;
            this.dpkHD.Value = DateTime.Now;
            this.cbxNV.SelectedIndex = 0;

            this.grvDetail.DataSource = null;
        }

        private void btnDeleteInvoice_Click(object sender, EventArgs e)
        {
            Guid Id = this.GetSelectedID();
            if (Id != Guid.Empty)
            {
                ManagerDocumentBL.DeleteInvoice(Id);
                this.RefreshGridView();
            }
        }

        private Guid GetSelectedID()
        {
            Guid result = Guid.Empty;
            DataGridViewRow selectedRow = this.grvDocument.SelectedRows[0];
            if (selectedRow != null)
            {
                result = Guid.Parse(selectedRow.Cells[ID_HD].Value.ToString());
            }
            return result;
        }

        private void btnSave_Click(object sender, EventArgs e)
        {
            if (ValidateData())
            {
                DocumentItem docItem = null;
                if (this._selectedID == Guid.Empty)
                    docItem = this.CreateOrUpdateDocumentItem(null);
                IList<DocumentDetailItem> docDetail = this.GetAlllDetail();

                ManagerDocumentBL.CreateNewInvoice(docItem, docDetail);
                this.RefreshGridView();
            }
        }

        private bool ValidateData()
        {
            if (string.IsNullOrWhiteSpace(txtMaHD.Text))
            {
                Ultilities.GetErrorMessage("Vui lòng không để trống");
                return false;
            }
            else if (ManagerDocumentBL.CheckExist(this.txtMaHD.Text))
            {
                Ultilities.GetErrorMessage("Trùng mã hoá đơn");
                return false;
            }
            else if (this.grvDetail.Rows == null || this.grvDetail.Rows.Count <= 0)
            {
                Ultilities.GetErrorMessage("Vui lòng thêm chi tiết hoá đơn");
                return false;
            }
            return true;
        }

        private void btnCancel_Click(object sender, EventArgs e)
        {
            this.CancelModified();
        }

        private void btnAddDetail_Click(object sender, EventArgs e)
        {
            if (this._selectedID != Guid.Empty) return;

            this.grvDetail.Rows.Add(Guid.Parse(this.cbxSP.SelectedValue.ToString()), this.cbxSP.Text, this.txtSL.Text);

        }

        private void btnDeleteDetail_Click(object sender, EventArgs e)
        {
            if (this._selectedID != Guid.Empty) return;
        }


    }
}
